package com.superfish.cutieshop.activities;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.superfish.cutieshop.BaseActivity;
import com.superfish.cutieshop.BaseConfig;
import com.superfish.cutieshop.R;
import com.superfish.cutieshop.been.Notify;
import com.superfish.cutieshop.dialog.AppLoading;
import com.superfish.cutieshop.utils.CommonUtil;
import com.superfish.cutieshop.utils.LogTest;
import com.superfish.cutieshop.utils.MessageHandlerList;
import com.superfish.cutieshop.utils.TimeUtils;

import java.util.List;

@ContentView(R.layout.activity_web)
public class WebActivity extends BaseActivity {

    @ViewInject(R.id.btnContainer)
    private LinearLayout mBtnContainer;
    @ViewInject(R.id.container)
    private View mContainer;


    public static void open(Activity act, String url, String title, boolean isUser) {
        Intent i = new Intent(act, WebActivity.class);
        i.putExtra("isUser", isUser);
        i.putExtra("url", url);
        i.putExtra("title", title);
        i.putExtra("isNotify", false);
        open(act, i);
    }

    public static void open(Activity act, String url, String title, boolean isUser, boolean isNotify) {
        Intent i = new Intent(act, WebActivity.class);
        i.putExtra("isUser", isUser);
        i.putExtra("url", url);
        i.putExtra("title", title);
        i.putExtra("isNotify", isNotify);
        open(act, i);
    }

    private boolean isUser;//判断是否是用户协议 还是买手计划
    private String mUrl;//跳转链接
    private String title;
    private boolean isNotify;

    private DbUtils db;

    @ViewInject(R.id.toolbar)
    private Toolbar mToolbar;
    @ViewInject(R.id.webView)
    private WebView mWebView;

    private boolean isFailed;

    private AppLoading loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loading = new AppLoading(WebActivity.this);
        loading.setTips(R.string.apploading_loading);
        db = DbUtils.create(this);
        isUser = getIntent().getBooleanExtra("isUser", true);//默认是用户协议
        mUrl = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        isNotify = getIntent().getBooleanExtra("isNotify", false);
        if (isNotify) {
            try {
                List<Notify> list = db.findAll(Selector.from(Notify.class).where("value", "=", mUrl));
                for (Notify n : list) {
                    n.read = BaseConfig.NOTIFICATION_READ;
                }
                db.updateAll(list);
            } catch (DbException e) {
                e.printStackTrace();
            }
            MessageHandlerList.sendMessage(NotifyActivity.class, BaseConfig.MessageCode.ON_READ_UMMESSAGE);
        }
        mBtnContainer.setVisibility(isUser ? View.GONE : View.VISIBLE);
        mToolbar.setTitle("");
        setAppTitle(title);
        mToolbar.setNavigationIcon(R.drawable.btn_back_bar);
        mToolbar.setBackgroundColor(getResources().getColor(TimeUtils.aTheme()));
        getStatusBar().setBackgroundColor(getResources().getColor(TimeUtils.aTheme()));
        setSupportActionBar(mToolbar);
        if (android.os.Build.VERSION.SDK_INT > 8) {// 判断sdk版本，使用不用的api消除fedingedge
            mWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        } else {
            mWebView.setFadingEdgeLength(0);
        }
        showLoading();
        mWebView.loadUrl(mUrl);
        initEvents();
    }


    protected void initEvents() {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogTest.wlj("----" + url);
                // report@ipicopico.com 为了配合IOS做变更
                if (url.startsWith("emailto:")) {
                    loading.show();
                    //执行发邮件
                    String email = url.substring("emailto:".length(), url.length());
                    sendEmail(email);
                    loading.dismiss();
                    return true;
                }
                mWebView.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view,
                                           SslErrorHandler handler, android.net.http.SslError error) {
                handler.proceed();

            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                isFailed = true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                // 判断网络链接
                if (isFailed) {
                    showNetfailed();
                } else {
                    showContent();
                }

            }
        });
        mWebView.setDownloadListener(new MyWebViewDownLoadListener());
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        });
    }

    @OnClick(R.id.qq)
    /** 联系QQ **/
    public void onClickQQ(View v) {
        CommonUtil.openQQChat(WebActivity.this, "651319154");
    }

    private String mEmail = "report@ipicopico.com";

    @OnClick(R.id.email)
    public void onClickReport(View v) {
        sendEmail(mEmail);
    }

    private void sendEmail(String mEmail) {
        try {
            Uri uri = Uri.parse("mailto:" + mEmail);
            String[] email = {mEmail};
            Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
            intent.putExtra(Intent.EXTRA_CC, email); // 抄送人
            intent.putExtra(Intent.EXTRA_SUBJECT, ""); // 主题
            intent.putExtra(Intent.EXTRA_TEXT, ""); // 正文
            startActivity(Intent.createChooser(intent, "请选择邮件类应用"));
        } catch (Exception e) {
            //执行多选
            String[] email = {mEmail}; // 需要注意，email必须以数组形式传入
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("message/rfc822"); // 设置邮件格式
            intent.putExtra(Intent.EXTRA_EMAIL, email); // 接收人
            intent.putExtra(Intent.EXTRA_CC, email); // 抄送人
            intent.putExtra(Intent.EXTRA_SUBJECT, ""); // 主题
            intent.putExtra(Intent.EXTRA_TEXT, ""); // 正文
            startActivity(Intent.createChooser(intent, "请选择邮件类应用"));
        }
    }

    private class MyWebViewDownLoadListener implements DownloadListener {
        @Override
        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype, long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }


    public void showLoading() {
        mContainer.setVisibility(View.GONE);
        mPageState.showLoading();
    }

    public void showNetfailed() {
        mContainer.setVisibility(View.GONE);
        mPageState.showNetFailed();
        mPageState.setOnReloadListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isFailed = false;
                showLoading();
                mWebView.loadUrl(mUrl);
            }
        });
    }

    public void showContent() {
        mContainer.setVisibility(View.VISIBLE);
        mPageState.hide();
    }


}
